Step 22: MongoDB & Mongoose
In this section, we add persistence to Bookmark API. Adding persistence to an application means storing data so that it persists beyond the lifetime of the application. This goal is typically achieved by storing application data in a database.
A database is a shared collection of related data.
We will be using a database called MongoDB to add persistence to Bookmark API.
Set up a MongoDB cluster in the cloud by following the instructions provided in the “readings” of this website!
We will use a library called Mongoose to work with MongoDB in Express apps. Add mongoose as a dependency:
yarn add mongoose
Mongoose is an object document mapping (ODM) that sits on top of Node MongoDB driver.
Let’s add a new file db.js
to the src/data
folder with the following content:
import mongoose from "mongoose";
const URI = "mongodb+srv://bookmark-api-admin:<password>@bookmark-api.btuoger.mongodb.net/dev?retryWrites=true&w=majority";
const option = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
export function connect() {
mongoose.connect(URI, option);
mongoose.connection.on("error", (err) => {
console.log("Could not connect to MongoDB");
console.log(err);
});
mongoose.connection.on("open", () => {
console.log("Connected to MongoDB!");
});
}
You should use your own connection URI. Moreover, you must replace
<password>
with the password generated for your MongoDB user.
Save the files and run the API server.
You should see “Connected to MongoDB!” message.
Aside: We should not store the connection URI in the source code.
Instead, we can create an environment variable DB_URI
in our local machine and store the connection URI in that variable. The process of creating environment variables varies in different environments (e.g., Mac vs. Windows). There is a Node package that makes this as easy as defining variables in a text file.
Add dotenv-cli
as a development dependency:
yarn add -D dotenv-cli
Create a .env
file at the root of this repository. Open the file and add the following:
DB_URI=mongodb+srv://bookmark-api-admin:<password>@bookmark-api.btuoger.mongodb.net/dev?retryWrites=true&w=majority
Make sure to
- replace
<password>
with the the password generated for your MongoDB user.- add
.env
to your.gitignore
so you don't push it to the repository!
Update src/data/db.js
by changing URI
declaration as follows:
const URI = process.env.DB_URI;
Next, update package.json
to change the dev
command as follows:
"dev": "dotenv -e .env nodemon server.js",
Run the app again!
Aside: You should not use .env
in Heroku! On Heroku, instead of .env
you should add the environment variables to the “Config Vars.”
Open your Heroku dashboard. Then open your app. Next, go to Settings and find the “Config Vars.” Here is where you enter the environment variables such as DB_URI
.